package com;

import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import java.io.*;
import java.net.Socket;

public class HTTPSClient {

    public static void main(String[] args) {

        if(args.length == 0){

            System.out.println("Usage: java HTTPSClient2 host");

            return;

        }

        int port = 443;

        String host = args[0];

        SSLSocketFactory sslSocketFactory = (SSLSocketFactory) SSLSocketFactory.getDefault();


        try (SSLSocket socket = (SSLSocket) sslSocketFactory.createSocket(host,port);){

            String[] supported = socket.getSupportedCipherSuites();

            socket.setEnabledCipherSuites(supported);

            //发送请求
            Writer writer = new OutputStreamWriter(socket.getOutputStream(),"UTF-8");

            writer.write("GET https://" + host + "/ HTTP/1.1\r\n");
            writer.write("Host: " + host);
            writer.write("\r\n");

            writer.flush();

            //接受应答
            BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));

            String s;
            int length = 0;
            while ((s = reader.readLine()) != null && !s.equals("")){
                System.out.println(s);
                if(s.startsWith("Content-Length: ")) length = Integer.parseInt(s.substring(s.indexOf("Content-Length: ")+16,s.length()));
            }
            System.out.println();

            /*String contentLength = reader.readLine();
            int length = Integer.MAX_VALUE;
            try {
                length = Integer.parseInt(contentLength.trim(),16);
            }catch (NumberFormatException e){

            }
            System.out.println(contentLength);*/

            //System.out.println(length);

            int c;
            int i = 0;
            while ((c = reader.read()) != -1 && i++<length){

                System.out.print((char)c);

            }

            System.out.println();

        } catch (IOException e) {
            e.printStackTrace();
        }


    }

}
